package com.panopset.gui;

import java.awt.FlowLayout;

import javax.swing.JPanel;
import javax.swing.JPasswordField;

import static com.panopset.Util.*;

import com.panopset.centralen.resource.DocumentManager;

/**
 * Widgets.
 *
 * @author Karl Dinwiddie
 *
 */
public final class Widgets {

    /**
     * Number of columns for the password.
     */
    private static final int COLUMNS = 20;

    /**
     * Password key.
     */
    private static final String PWDKEY = "com.panopset.wg";

    /**
     * Prompt for password.
     *
     * @param documentManager
     *            Document manager that the calling program is responsible for
     *            saving and retrieving. If provided, a "remember" check box
     *            will be added to the dialog.
     * @return password.
     */
    public static String promptForPassword(
            final DocumentManager documentManager) {
        JPasswordField jpw = new JPasswordField();
        JPanel p = new JPanel(new FlowLayout());
        p.add(jpw);
        TypicalDialog d = new TypicalDialog.Builder(
                "Please enter your password").centerPanel(p).remember()
                .construct();
        d.getPanel().setLayout(new FlowLayout());
        jpw.setColumns(COLUMNS);
        documentManager.load();
        String pwd = documentManager.get(PWDKEY);
        if (isPopulated(pwd)) {
            return pwd;
        }
        d.getFrame().setVisible(true);
        char[] pwa = jpw.getPassword();
        documentManager.save();
        if (pwa == null) {
            return "";
        } else {
            return new String(jpw.getPassword());
        }
    }

    /**
     * Prevent instantiation.
     */
    private Widgets() { }
}
